//
//  CXNetworkTool.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/21.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import AFNetworking
/*
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];

*/
class CXNetworkTool: AFHTTPSessionManager {
    /// 定义一个单例充当全局访问点
    static let sharedTool:CXNetworkTool = {
        let tool = CXNetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    ///  网络请求
    func request(method:CXRequestMethod = .GET, urlString:String, parameters:AnyObject?, finished:(( response:AnyObject?, error:NSError? )-> Void)) {
        ///  将失败和成功后回调的闭包进行整合,作为参数传入AFN的方法中
        let success = {(dataTask:NSURLSessionDataTask, response: AnyObject?) -> () in
            finished(response: response, error: nil)
        }
        let failure = {(dataTask: NSURLSessionDataTask?, error: NSError) -> () in
            finished(response: nil, error: error)
        }
        
        if method == .POST {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
// MARK: - 将viewModel中的请求链接与参数封装
extension CXNetworkTool {
    ///  请求获取用户的asscess token
    func loadUserInfo(code: String, finished: (response:AnyObject?, error: NSError?) -> Void) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": CXWB_CLIENT_ID,
            "client_secret": CXWB_CLIENT_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": CXWB_REDIRECT_ID
        ]
        
        request(.POST, urlString: urlStr, parameters: params, finished: finished)
    }
    ///  请求获取用户信息 （通过access token）
    func getUserInfo(accessToken: String, uid: String, finished: (response: AnyObject?, error: NSError?) -> Void) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token":accessToken,
            "uid":uid
        ]
        request(urlString: urlStr, parameters: params, finished: finished)
    }
    ///  获取首页的微博状态信息
    func loadHomeStatuses(accessToken: String, sinceId: Int64 = 0, maxId: Int64 = 0, finished: (response: AnyObject?, error: NSError?) -> Void) {
        
        let urlStr = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params = [
            "access_token": accessToken,
            "since_id": "\(sinceId)",
            "max_id": "\(maxId)"
        ]
        request(urlString: urlStr, parameters: params, finished: finished)
    }
}
// MARK: - 发送微博状态相关
extension CXNetworkTool {
    
    ///  上传文件,可以被用于上传图片
    func upload(urlstring urlstring: String, data: [String: NSData], params:AnyObject?, finished:((response: AnyObject?, error: NSError?) -> Void)) {
        
        POST(urlstring, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            // 遍历上传文件
            for (key,value) in data {
                // 拼接要上传的数据
                formData.appendPartWithFileData(value, name: key, fileName: "aaa", mimeType: "application/octet-stream")
            }
            }, progress: nil, success: { (_, response) -> Void in
                // 请求成功的回调
                finished(response: response, error: nil)
            }) { (_, error) -> Void in
                // 请求失败的回调
                finished(response: nil, error: error)
        }
    }
    ///  发送微博：纯文本(包含表情)
    func sendStatus(puretext status: String, accessToken: String, finished: (response: AnyObject?, error: NSError?) -> Void) {
        
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        //直接调用封装的request方法
        request(.POST, urlString: urlStr, parameters: params, finished: finished)
    }
    func upload(image image: UIImage, accessToken: String, status: String, finished: (response: AnyObject?, error: NSError?) -> Void) {
        
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        //pic是新浪微博服务器用来接收图片的字段名
        let formData = ["pic": UIImagePNGRepresentation(image)!]
        upload(urlstring: urlStr, data: formData, params: params, finished: finished)
    }
}
///  http请求方法名的枚举
enum CXRequestMethod:String {
    
    case GET = "GET"
    case POST = "POST"
}
